<template>
    <div class="common-layout">
        <el-container>
            <!-- <el-header style="display: flex; align-items: center;">
                <div class="item-text" style="flex: 1;"></div>
                <div style="flex: 1;">
                    <el-row align="middle" :gutter="20" justify="start">
                        <el-col :span="8">
                            <el-input v-model="searchModel.Code" placeholder="订单编号或编码" clearable
                                style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                                @keyup.enter.native="SearchList" />
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="primary" @click="SearchList"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                <i class="el-icon-search"></i>搜索
                            </el-button>
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="success" @click="SearchList"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                <i class="el-icon-refresh"></i>刷新
                            </el-button>
                        </el-col>
                        <el-col :span="4" style="display: flex; align-items: center; justify-content: flex-start;">
                            <el-button type="success" @click="InsertData()"
                                style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                                <i class="el-icon-plus"></i>新增
                            </el-button>
                        </el-col>
                    </el-row>
                </div>
            </el-header> -->

            <div class="view-header" style="display: flex; justify-content: space-between;margin-top: 15px;">
                <div class="desc-text">
                    <i class="el-icon-s-grid" />
                    <span>材料出库列表</span>
                </div>
                <div>
                   <el-input v-model="searchModel.Code" placeholder="订单编号或编码" clearable
                                style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                                @keyup.enter.native="SearchList" />
                    <el-button type="primary" @click="SearchList">
                        <i class="el-icon-search"></i>搜索
                    </el-button>
                    <el-button type="success" @click="SearchList">
                        <i class="el-icon-refresh"></i>刷新
                    </el-button>
                    <el-button type="success" @click="InsertData()">
                        <i class="el-icon-plus"></i>新增
                    </el-button>
                </div>
            </div>


            <!-- <el-main style="display: flex; flex-direction: column; gap: 30px;"> -->
            <div class="mian-flex">
                <!-- 订单列表 -->
                <div class="table-info mes-table" v-loading="loading">
                    <!-- <div class="table-container"> -->
                    <!-- <div class="section-title">材料出库列表</div> -->

                    <!--  设置固定高度，只在表格内部滚动 -->
                    <el-table :data="detailTableData" style="width: 100%;" stripe="true" border="true" max-height="550">
                        <el-table-column type="index" width="50" />
                        <el-table-column type="selection" width="50" align="center" />
                        <el-table-column label="单据编号" prop="code" width="200" align="center">
                            <template #default="scope">
                                <el-link type="primary" @click="showOrderDetail(scope.row)">
                                    {{ scope.row.code }}
                                </el-link>
                            </template>
                        </el-table-column>
                        <el-table-column prop="voucherDate" label="单据日期" width="200" align="center" />
                        <!-- 业务类型 -->
                        <el-table-column label="业务类型" width="100" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.busiType === 1" style="font-weight:bold;">
                                    直接领料
                                </span>
                                <span v-else-if="scope.row.busiType === 2" style="font-weight:bold;">
                                    直接退料
                                </span>
                                <span v-else style="color:red; font-weight:bold;">&nbsp;</span>
                            </template>
                        </el-table-column>

                        <!-- 部门名称 -->
                        <el-table-column label="部门名称" width="150" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.departmentName">{{ scope.row.departmentName }}</span>
                                <span v-else style="color:red; font-weight:bold;">&nbsp;</span>
                            </template>
                        </el-table-column>

                        <!-- 领用人 -->
                        <el-table-column label="领用人" width="150" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.clerkName">{{ scope.row.clerkName }}</span>
                                <span v-else style="color:red; font-weight:bold;">&nbsp;</span>
                            </template>
                        </el-table-column>

                        <!-- 生产计划 -->
                        <el-table-column label="生产计划" width="150" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.clerkName">{{ scope.row.productPlanCode }}</span>
                                <span v-else style="color:red; font-weight:bold;">&nbsp;</span>
                            </template>
                        </el-table-column>

                        <!-- 仓库 -->
                        <el-table-column label="仓库" width="150" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.warehouseName">{{ scope.row.warehouseName }}</span>
                                <span v-else style="color:red; font-weight:bold;">&nbsp;</span>
                            </template>
                        </el-table-column>

                        <!-- 状态 -->
                        <el-table-column label="状态" width="100" align="center">
                            <template #default="scope">
                                <span v-if="scope.row.status === 181" style="font-weight:bold;">
                                    未审
                                </span>
                                <span v-if="scope.row.status === 189" style="font-weight:bold;">
                                    已审核
                                </span>
                            </template>
                        </el-table-column>
                        <el-table-column prop="createdId" label="创建人" width="100" align="center" />
                        <el-table-column prop="createdTime" label="创建时间" width="200" align="center" />
                        <el-table-column fixed="right" label="操作" min-width="230">
                            <template #default="scope">
                                <!-- {{ scope.row }} -->
                                <el-button link type="primary" size="small"
                                    @click="ReviewMaterialOutOrder(scope.row.orderId)">审核</el-button>
                                <el-button link type="primary" size="small"
                                    @click="DeleteMaterialOutOrder(scope.row.orderId)">删除</el-button>
                                <el-button link type="primary" size="small"
                                    @click="UnReviewMaterialOutOrder(scope.row.orderId)">弃审</el-button>
                            </template>
                        </el-table-column>
                    </el-table>

                    <div class="demo-pagination-block table-pagination"
                        style="display: flex; justify-content: flex-end;">
                        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                            :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                            :total="totalCount" @current-change="handleCurrentChange" @size-change="handleSizeChange" />
                    </div>

                </div>
            </div>
            <!-- 新增数据弹窗 -->
            <el-dialog v-model="insertDialogVisiable" class="fixed-size-dialog" width="80%"
                :before-close="handleInsertClose">
                <!-- 自定义标题插槽 -->
                <template #title>
                    <div style="display: flex; flex-direction: column;">
                        <span style="font-size: 20px; font-weight: bold;">新增材料出库单</span>
                    </div>
                </template>

                <!-- 上半部分表单 -->
                <div class="dialog-body">
                    <div class="form-section">
                        <el-form :model="insertForm" label-width="120px" class="order-detail-form"
                            label-position="right">
                            <el-row :gutter="20">
                                <el-col :span="12">
                                    <el-form-item label="单据日期" width="150">
                                        <el-date-picker v-model="insertForm.orderDate" type="date" placeholder="选择日期"
                                            style="width: 100%" />
                                    </el-form-item>
                                </el-col>

                                <el-col :span="12">
                                    <el-form-item label="单据编号" width="150">
                                        <el-input v-model="insertForm.orderNo" disabled
                                            style="width: 100%" />
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="业务类型:">
                                        <el-select v-model="insertForm.businessType" placeholder="请选择业务类型"
                                            style="width: 100%;">
                                            <el-option label="直接领料" :value="1" />
                                            <el-option label="直接退料" :value="2" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>
                                <el-col :span="12">
                                    <el-form-item label="生产车间" width="150">
                                        <el-select v-model="insertForm.departmentName" placeholder="选择生产车间"
                                            style="width: 100%">
                                            <el-option v-for="item in departmentOptions" :key="item.id"
                                                :label="item.departmentName" :value="item.departmentName" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="12">
                                    <el-form-item label="领用人" width="150">
                                        <el-select v-model="insertForm.employeesName" placeholder="选择领用人"
                                            style="width: 100%">
                                            <el-option v-for="item in employeeOptions" :key="item.id"
                                                :label="item.employeesName" :value="item.employeesName" />
                                        </el-select>
                                    </el-form-item>
                                </el-col>

                                <el-col :span="12">
                                    <el-form-item label="生产计划" width="150">
                                        <el-input
                                            v-model="insertForm.productPlanCode"
                                            readonly
                                            @click="selectIdChange"
                                            placeholder="选择生产计划"
                                        />
                                    </el-form-item>
                                </el-col>

                            </el-row>
                        </el-form>
                    </div>
                </div>

                <!-- 分割线 -->
                <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

                <!-- 下半部分：可新增数据的表格 -->
                <div class="table-section">
                    <el-button type="primary" @click="addRow" style="margin-bottom: 10px;">新增一行</el-button>
                    <el-table :data="insertTableData" style="width: 100%;" border stripe>
                        <el-table-column type="index" label="序号" width="50" />

                        <el-table-column label="仓库" width="150">
                            <template #default="scope">
                                <el-select v-model="scope.row.warehouseId" placeholder="选择仓库" style="width: 100%"
                                    @change="value => onWarehouseOrInventoryChange(scope.row)">
                                    <el-option v-for="item in warehouseOptions" :key="item.id"
                                        :label="item.warehouseName" :value="item.id" />
                                </el-select>
                            </template>
                        </el-table-column>

                        <el-table-column label="存货名称" width="150">
                            <template #default="scope">
                                <el-input v-model="scope.row.inventoryName" readonly
                                    @click="openInventoryDialog(scope.row)" />
                            </template>
                        </el-table-column>


                        <el-table-column prop="unitName" label="计量单位" width="120" />
                        <el-table-column prop="quantity" label="数量" width="165">
                            <template #default="scope">
                                <el-input-number v-model="scope.row.quantity" :min="0" />
                            </template>
                        </el-table-column>

                        <el-table-column prop="specificationModel" label="规格型号" width="150">
                            <!-- <template #default="scope">
                                <el-input v-model="scope.row.spec" placeholder="规格型号" />
                            </template> -->
                        </el-table-column>
                        <el-table-column prop="existingQuantity" label="现存量" width="150">
                            <template #default="scope">
                                <el-input v-model="scope.row.existingQuantity" readonly />
                            </template>
                        </el-table-column>

                        <el-table-column prop="stockRemark" label="现存量说明" width="300">
                            <template #default="scope">
                                <el-input v-model="scope.row.stockRemark" placeholder="说明" />
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="100">
                            <template #default="scope">
                                <el-button type="danger" @click="removeRow(scope.$index)" size="small">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <template #footer>
                    <el-button @click="insertDialogVisiable = false">取消</el-button>
                    <el-button type="primary" @click="saveInsert">保存</el-button>
                </template>
            </el-dialog>

            <!-- 存货选择弹窗 -->
            <el-dialog v-model="inventoryDialogVisible" width="900px" :close-on-click-modal="false"
                :destroy-on-close="true" top="5vh" class="fixed-inventory-dialog">
                <template #title>
                    <span style="font-weight: bold;">选择存货</span>
                </template>

                <div style="display: flex; justify-content: flex-end; margin-bottom: 10px;">
                    <el-input v-model="inventorySearchData.Code" placeholder="存货编号或编码" clearable
                        style="width: 240px; height: 35px; font-size: 15px; padding: 0 15px;"
                        @keyup.enter.native="handleSearch" />

                    <el-button type="primary" @click="handleSearch"
                        style="height: 35px; font-size: 30px; padding: 0 20px; cursor: pointer; min-width: 100px;">
                        搜索
                    </el-button>
                </div>

                <!-- 表格滚动容器 -->
                <div class="table-scroll-wrapper">
                    <el-table :data="inventoryOptions" stripe border style="width: 100%;"
                        @selection-change="handleSelectionChange">
                        <!-- 序号列 -->
                        <el-table-column type="index" width="50" />
                        <!-- 选择列 -->
                        <el-table-column type="selection" width="50" />
                        <el-table-column prop="inventoryCode" label="存货编码" width="150" />
                        <el-table-column prop="inventoryName" label="存货名称" width="200" />
                        <el-table-column prop="unitName" label="计量单位" width="120" />
                        <el-table-column prop="specificationModel" label="规格型号" width="180" />
                        <el-table-column prop="inventoryClassName" label="所属类别" width="180" />
                    </el-table>
                </div>

                <!-- 分页部分 -->
                <div class="demo-pagination-block" style="display: flex; justify-content: flex-end; margin-top: 20px;">
                    <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                        :page-sizes="[15, 30, 50, 80, 100]" layout="total, sizes, prev, pager, next, jumper"
                        :total="totalCount" @current-change="handleCurrentChangeInventory"
                        @size-change="handleSizeChangeInventory" />
                </div>

                <!-- 底部按钮 -->
                <template #footer>
                    <div style="text-align: right;">
                        <el-button @click="inventoryDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="confirmInventory">确定</el-button>
                    </div>
                </template>
            </el-dialog>


        </el-container>
    </div>
    <!-- 材料出库单明细弹窗 -->
    <el-dialog v-model="detailDialogVisible" class="order-detail-dialog" :lock-scroll="true" width="80%"
        :before-close="handleClose">
        <!-- 自定义标题 -->
        <template #title>
            <div style="display: flex; flex-direction: column;">
                <span style="font-size: 20px; font-weight: bold;">材料出库明细</span>
            </div>
        </template>
        <!-- 上半部分表单 -->
        <div class="dialog-body">
            <div class="form-section">
                <el-form :model="insertForm" label-width="120px" class="order-detail-form"
                    label-position="right">
                    <el-row :gutter="20">
                        <el-col :span="12">
                            <el-form-item label="单据日期" width="150">
                                <el-date-picker v-model="orderDetail.voucherDate" type="date" disabled placeholder="选择日期"
                                    style="width: 100%" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="单据编号" width="150">
                                <el-input v-model="orderDetail.code" placeholder="请输入单据编号" disabled
                                    style="width: 100%" />
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="业务类型:">
                                <el-select v-model="orderDetail.busiType" placeholder="请选择业务类型" disabled
                                    style="width: 100%;">
                                    <el-option label="直接领料" :value="1" />
                                    <el-option label="直接退料" :value="2" />
                                </el-select>
                            </el-form-item>
                        </el-col>
                        <el-col :span="12">
                            <el-form-item label="生产车间" width="150">
                                <el-select v-model="orderDetail.departmentId" placeholder="选择生产车间" disabled
                                    style="width: 100%">
                                    <el-option v-for="item in departmentOptions" :key="item.id"
                                        :label="item.departmentName" :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="领用人" width="150">
                                <el-select v-model="orderDetail.clerkId" placeholder="选择领用人" disabled
                                    style="width: 100%">
                                    <el-option v-for="item in employeeOptions" :key="item.id"
                                        :label="item.employeesName" :value="item.id" />
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="12">
                            <el-form-item label="生产计划" width="150">
                                <el-input v-model="orderDetail.productPlanCode" disabled
                                    style="width: 100%" />
                            </el-form-item>
                        </el-col>

                    </el-row>
                </el-form>
            </div>
        </div>

        <!-- 分割线 -->
        <div style="margin: 10px 0; border-bottom: 1px solid #dcdfe6;"></div>

        <!-- 下半部分：可新增数据的表格 -->
        <div class="table-section">
            <el-table :data="orderDetail.materialOutboundOrderDetails" style="width: 100%;" border stripe>
                <el-table-column type="index" label="序号" width="50" />

                <el-table-column label="仓库" min-width="150">
                    <template #default="scope">
                        <el-select v-model="scope.row.warehouseId" placeholder="选择仓库" style="width: 100%" disabled
                            @change="value => onWarehouseOrInventoryChange(scope.row)">
                            <el-option v-for="item in warehouseOptions" :key="item.id"
                                :label="item.warehouseName" :value="item.id" />
                        </el-select>
                    </template>
                </el-table-column>

                <el-table-column label="存货名称" min-width="150">
                    <template #default="scope">
                        <el-input v-model="scope.row.inventoryName" readonly disabled
                            @click="openInventoryDialog(scope.row)" />
                    </template>
                </el-table-column>


                <el-table-column prop="unitName" label="计量单位" min-width="120" />
                <el-table-column prop="baseQuantity" label="数量" width="165">
                    <template #default="scope">
                        <el-input-number v-model="scope.row.baseQuantity" :min="0" disabled />
                    </template>
                </el-table-column>

                <el-table-column prop="specificationModel" label="规格型号" width="150">
                    <!-- <template #default="scope">
                        <el-input v-model="scope.row.spec" placeholder="规格型号" />
                    </template> -->
                </el-table-column>
                <!-- <el-table-column label="操作" width="100">
                    <template #default="scope">
                        <el-button type="danger" @click="removeRow(scope.$index)" size="small">删除</el-button>
                    </template>
                </el-table-column> -->
            </el-table>
        </div>

        <template #footer>
            <el-button @click="detailDialogVisible = false">关闭</el-button>
        </template>
    </el-dialog>

    <!-- 生产计划 -->
    <dialog-com
    ref="selectDocumentIdRef"
    :title="'生产计划'"
    :width="'80%'"
    class="plan-dialog"
    @confirm-change="confirmSelectDocumentChange"
    @close-change="closeSelectDocumentChange"
  >
    <template #content>
      <div style="margin-bottom: 10px">
        <el-input
          v-model="documentId"
          clearable
          style="width: 200px"
          placeholder="生产计划"
        />
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="queryDocumentIdChange"
        >
          <i class="el-icon-search"></i>查询
        </el-button>
      </div>
      <data-table
        ref="documentIdTableRef"
        class="plan-table"
        :tableKey="documentIdTableKey"
        @table-selection-change="documentIdSelectionChange"
      >
      </data-table>
      <!-- 分页 -->
      <div class="table-pagination">
        <el-pagination
          v-model:current-page="planCurrentPage"
          v-model:page-size="planPageSize"
          :page-sizes="[15, 30, 50, 80, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalPage"
          @size-change="PlanHandleSizeChange"
          @current-change="PlanHandleCurrentChange"
        />
      </div>
    </template>
  </dialog-com>
</template>

<script setup>
import { ref, watch, onMounted, reactive, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
    orderDetailSearchList,
    orderInfoSearch,
    getWareHouse,
    getInventory,
    InventorySearch,
    getDepemendents,
    getWareHouses,
    getEmployees,
    AddMaterialOutboundOrder,
    MaterialOutboundOrderSearch,
    getExistingQuantity,
    ReviewMaterialOut,
    DeleteMaterialOut,
    UnReviewMaterialOrder,
    getMaterialOutboundOrderCode
} from '../../extension/V2/MaterialOut'

import {
  getProductPlanList,
} from "@/api/productionManagement/productInspectionForm.js";

// 搜索条件模型
const searchModel = ref({ Code: '' })

// 表格数据与分页数据
const detailTableData = ref([]) // 订单展示明细模型
const detailDialogVisible = ref(false)
const orderDetail = ref({})
const insertDialogVisiable = ref(false)
let loading = false

const totalCount = ref(0)
const currentPage = ref(1)
const pageSize = ref(15)

const orderInfodetail = ref([])

// 生产计划
const documentId = ref('')
const planCurrentPage = ref(1)
const planPageSize = ref(15)
const totalPage = ref(0)
const selectDocumentId = ref([])
const documentIdTableKey = ref([
    {
        value: "productPlanCode",
        name: "单据编号",
        minWidth: "250",
        sortable: false,
        algin: 'left'
    },
    { value: "remark", name: "备注", minWidth: "250",  algin: 'left' },
    { value: "creator", name: "创建人", minWidth: "250",  algin: 'left' },
    { value: "createDate", name: "创建时间", minWidth: "250",  algin: 'left' },
])

// 模板引用
const selectDocumentIdRef = ref(null)
const documentIdTableRef = ref(null)

// 选择单据编号弹出选择框，并获取单据编号列表数据
const selectIdChange = () => {
  selectDocumentIdRef.value.dialogVisible = true
  // 获取单据编号列表数据
  nextTick(() => {
    queryDocumentIdChange()
  })
}

// 获取单据编号列表即生产计划列表
const queryDocumentIdChange = async () => {
  try {
    const params = {
      ProductPlanCode: documentId.value,
      page: planCurrentPage.value,
      rows: planPageSize.value,
    }
    const result = await getProductPlanList(params)
    if (result.status === 0) {
      documentIdTableRef.value.tableData = result.rows || []
      totalPage.value = result.total || 0
    } else {
      ElMessage.error('获取数据失败')
    }
  } catch (err) {
    console.error('数据异常:', err)
  }
}

// 切换条数
const PlanHandleSizeChange = (val) => {
  planPageSize.value = val
  planCurrentPage.value = 1
  queryDocumentIdChange()
}

// 切换页码
const PlanHleCurrentChange = (val) => {
  planCurrentPage.value = val
  queryDocumentIdChange()
}

// 选中的数据
const documentIdSelectionChange = (val) => {
  selectDocumentId.value = val ? JSON.parse(JSON.stringify(val)) : []
}

// 取消 选择单据编号
const closeSelectDocumentChange = () => {
  documentId.value = ''
  selectDocumentId.value = []
  documentIdTableRef.value.tableData = []
  planCurrentPage.value = 1
  planPageSize.value = 15
}

const confirmSelectDocumentChange = () => {
    if (selectDocumentId.value.length === 0) {
        return ElMessage.error("请至少选择一行数据");
    }
    if (selectDocumentId.value.length != 1) {
    return ElMessage.error("只能选择一行数据");
    }
    insertForm.value.productInspectionId = selectDocumentId.value[0].productPlan_Id
    insertForm.value.productPlanCode = selectDocumentId.value[0].productPlanCode
    closeSelectDocumentChange();
    selectDocumentIdRef.value.dialogVisible = false
}

// 新增表单
const insertForm = ref({
    orderDate: '',
    orderNo: '',
    businessType: '',
    workshop: '',
    receiver: '',
    warehouseName: '',
    productInspectionId: null,
    productPlanCode: ''
})

// 新增表格数据
const insertTableData = ref([])

// 添加行
const addRow = () => {
    insertTableData.value.push({
        inventoryName: '',       // 存货名称
        materialName: '',        // 材料名
        unitName: '',            // 单位
        quantity: 0,
        price: 0,
        amount: 0,
        existingQuantity: '',
        stockRemark: '',
        specificationModel: '',
        inventoryId: null,       // 前端存货id
        inventoryCode: '',       // 后端需要传的code
        warehouseId: null,       // 前端仓库id
        warehouseCode: ''        // 后端需要传的code
    })
}


// 删除行
const removeRow = (index) => {
    insertTableData.value.splice(index, 1)
}

// 保存新增
const saveInsert = async () => {
    // 数量不能大于现货量
    if(insertTableData.value.length > 0 && insertTableData.value.some(row => row.quantity > row.existingQuantity)) {
        return ElMessage.error('仓库现存不足')
    }
    if(!insertForm.value.productInspectionId) {
        return ElMessage.error('请选择生产计划')
    }
    try {
        // 找到部门、员工、仓库
        const department = departmentOptions.value.find(d => d.departmentName === insertForm.value.departmentName)
        const employee = employeeOptions.value.find(e => e.employeesName === insertForm.value.employeesName)
        const warehouse = warehouseOptions.value.find(w => w.warehouseName === insertForm.value.warehouseName)

        // 构造请求参数
        const payload = {
            code: insertForm.value.orderNo, // 单据编号
            voucherDate: insertForm.value.orderDate, // 单据日期
            busiType: insertForm.value.businessType, // 业务类型
            departmentId: department ? department.id : 0, // 部门ID
            clerkId: employee ? employee.id : 0, // 领用人ID
            warehouseId: warehouse ? warehouse.id : 0, // 仓库ID
            remark: insertForm.value.remark || '', // 备注
            productPlan_Id: insertForm.value.productInspectionId || null, // 生产计划ID
            materialOutboundOrderDetails: insertTableData.value.map(row => {
                const rowWarehouse = warehouseOptions.value.find(w => w.warehouseName === row.warehouseName)
                return {
                    warehouseId: rowWarehouse ? rowWarehouse.id : 0, // 仓库ID
                    quantity: row.quantity, // 数量
                    productionOrder: 0, // 生产订单ID（默认0）
                    inventoryId: row.inventoryId || 0 // 存货ID
                }
            })
        }

        console.log('请求参数payload:', payload)

        // 调用新增接口
        const res = await AddMaterialOutboundOrder(payload)
        console.log("接口返回res:", res)


        if (res) {
            ElMessage.success('新增保存成功')
            Search()
            insertDialogVisiable.value = false
            handleInsertClose() // 关闭时清空数据
        } else {
            ElMessage.error(res.msg || '保存失败')
        }
    } catch (err) {
        console.error('保存异常:', err)
        ElMessage.error('保存异常')
    }
}


// 关闭时清空数据
const handleInsertClose = () => {
    insertForm.value = { orderDate: '', orderNo: '', businessType: '', workshop: '', receiver: '', warehouseName: '', productInspectionId: null, productPlanCode: '' }
    insertTableData.value = []
    insertDialogVisiable.value = false
}

//新增
const InsertData = () => {
    insertDialogVisiable.value = true
    loadMaterialOutboundOrderCode()
}

// 审核材料出库单
const ReviewMaterialOutOrder = async (id) => {
    try {
        console.log("审核id:", id)
        const result = await ReviewMaterialOut(id)
        console.log("接口返回res:", result)

        if (result && result.item1 === true) {
            ElMessage.success((result && result.item2 && result.item2.msg) || '审核成功')
            Search()
        } else {
            ElMessage.error((result && result.item2 && result.item2.msg) || '审核失败')
        }
    } catch (err) {
        console.error('审核出库单异常:', err)
        ElMessage.error('审核异常')
    }
}


//删除材料出库单
const DeleteMaterialOutOrder = async (id) => {
    try {
        console.log("删除id:", id)
        const result = await DeleteMaterialOut(id)
        console.log("接口返回res:", result)

        if (result && result.item1 === true) {
            ElMessage.success((result && result.item2 && result.item2.msg) || '删除成功')   
            Search()
        } else {
            ElMessage.error((result && result.item2 && result.item2.msg) || '删除失败')
        }
    } catch (err) {
        console.error('删除出库单异常:', err)
        ElMessage.error('删除异常')
    }
}

//弃审材料出库单
const UnReviewMaterialOutOrder = async (id) => {
    try {
        console.log("弃审id:", id)
        const result = await UnReviewMaterialOrder(id)
        console.log("接口返回res:", result)

        if (result && result.item1 === true) {
            ElMessage.success((result && result.item2 && result.item2.msg) || '弃审成功')
            // 如果有查询列表的函数，可以这里调用刷新
            Search()
        } else {
            ElMessage.error((result && result.item2 && result.item2.msg)|| '弃审失败')
        }
    } catch (err) {
        console.error('弃审出库单异常:', err)
        ElMessage.error('弃审异常')
    }
}






// 仓库数据
const warehouseOptions = ref([])
const departmentOptions = ref([])
const employeeOptions = ref([])


// 仓库数据下拉展示
const loadWarehouses = async () => {
    try {
        console.log("111仓库数据加载")
        const result = await getWareHouse()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            warehouseOptions.value = result.rows || []
        } else {
            ElMessage.error(result.msg || '获取仓库数据失败')
        }
    } catch (err) {
        console.error('获取仓库数据异常:', err)
    }
}

// 部门数据下拉展示
const loadDepartment = async () => {
    try {
        console.log("111部门数据加载")
        const result = await getDepemendents()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            departmentOptions.value = result.rows || []
        } else {
            ElMessage.error(result.msg || '获取部门数据失败')
        }
    } catch (err) {
        console.error('获取部门数据异常:', err)
    }
}

// 员工数据下拉展示
const loadEmployees = async () => {
    try {
        console.log("111员工数据加载")
        const result = await getEmployees()
        // 假设后端返回 { status: 0, rows: [...] }
        if (result.status === 0) {
            employeeOptions.value = result.rows || []
        } else {
            ElMessage.error(result.msg || '获取员工数据失败')
        }
    } catch (err) {
        console.error('获取员工数据异常:', err)
    }
}

// 获取材料出库编码
const loadMaterialOutboundOrderCode = async () => {
    try {
        const result = await getMaterialOutboundOrderCode()
        if (result.ok) {
            insertForm.value.orderNo = result.data || ''
        } else {
            ElMessage.error(result.msg || '获取材料出库编码失败')
        }
    } catch (err) {
        console.error('获取材料出库编码数据异常:', err)
    }
}


// 存货选择弹窗处理
// 弹窗开关
const inventoryDialogVisible = ref(false)
// 存货列表数据
const inventoryOptions = ref([])
// 当前选中的存货（单选）
const selectedInventory = ref([])
// 当前正在编辑的订单行
const currentRow = ref(null)

const getInventoryParams = () => {
    const wheresArr = []
    if (inventorySearchData.Code) {
        wheresArr.push({
            name: 'inventoryCode',       // 搜索字段名
            value: String(inventorySearchData.Code || ''),
            displayType: 'like'          // 模糊匹配
        })
    }

    return {
        page: currentPage.value,
        rows: pageSize.value,
        sort: 'CreateDate',
        order: 'desc',
        wheres: JSON.stringify(wheresArr)  // 转为 JSON 字符串
    }
}


//加载数据
const loadingInventoryData = async () => {
    try {
        const params = getInventoryParams()
        console.log("数据加载成功getInventory（）")
        const res = await getInventory(params)
        inventoryOptions.value = res.rows || []
        totalCount.value = res.total || 0   // 更新总条数
    } catch (err) {
        console.error('加载存货数据异常:', err)
    }
}

onMounted(() => {
    loadWarehouses()
    loadDepartment()
    loadEmployees()
    loadingInventoryData()
})

// 打开弹窗并加载存货数据
const openInventoryDialog = async (row) => {
    currentRow.value = row
    inventoryDialogVisible.value = true
    currentPage.value = 1   // 打开时回到第一页

}

// 分页页码变化
const handleCurrentChangeInventory = (page) => {
    currentPage.value = page
    loadingInventoryData()
}

// 分页每页条数变化
const handleSizeChangeInventory = (rows) => {
    console.log("页大小变化:", rows)
    pageSize.value = rows
    currentPage.value = 1
    loadingInventoryData()
    console.log("页大小变化pageSize.value:", pageSize.value)
}

const inventorySearchData = reactive({
    Code: ''
}) // 用户输入的搜索内容

const handleSearch = () => {
    // 调用加载方法
    currentPage.value = 1   // 搜索时回到第一页
    loadingInventoryData()
}

// 表格勾选事件（这里用单选，所以取第一条）
const handleSelectionChange = (val) => {
    selectedInventory.value = val
}

// 仓库或存货变化时调用
const onWarehouseOrInventoryChange = async (row) => {
    console.log("仓库或存货变化时调用")

    // 找到仓库和存货对象（用于显示名称等）
    const warehouse = warehouseOptions.value.find(w => w.id === row.warehouseId)
    const inventory = inventoryOptions.value.find(i => String(i.id) === String(row.inventoryId))

    console.log("仓库:", warehouse)
    console.log("存货:", inventory)

    if (!warehouse || !inventory) {
        console.log("没选仓库或存货就返回")
        row.existingQuantity = ''
        return
    }

    // 调用后端接口，直接传 ID
    console.log("执行调用 getExistingQuantity()")
    const res = await getExistingQuantity({ warehouseId: row.warehouseId, inventoryId: row.inventoryId })

    if (res && res.ok) {
        row.existingQuantity = res.data // 后端返回的现存量
        console.log("返回的现存量:", row.existingQuantity)
    } else {
        row.existingQuantity = '' // 查不到时清空
    }

    // 保证显示名称
    row.warehouseName = warehouse.warehouseName
    row.inventoryName = inventory.inventoryName
}



// 确认选择
const confirmInventory = () => {
    if (!selectedInventory.value || selectedInventory.value.length === 0) {
        ElMessage.warning("请选择至少一条存货")
        return
    }

    // 当前行
    if (currentRow.value) {
        // 第一条存货回填到当前行
        const first = selectedInventory.value[0]
        currentRow.value.inventoryId = first.id // 存货ID（新增：保证保存时能带上）
        currentRow.value.inventoryCode = first.inventoryCode
        currentRow.value.inventoryName = first.inventoryName
        currentRow.value.unitName = first.unitName
        currentRow.value.specificationModel = first.specificationModel
        currentRow.value.inventoryClassName = first.inventoryClassName

        onWarehouseOrInventoryChange(currentRow.value)

        // 剩余选中存货新增行
        for (let i = 1; i < selectedInventory.value.length; i++) {
            const item = selectedInventory.value[i]
            insertTableData.value.push({
                warehouseName: '', // 可根据需要自动填仓库
                inventoryId: item.id, // 存货ID（新增：保证保存时能带上）
                inventoryCode: item.inventoryCode,
                inventoryName: item.inventoryName,
                unitName: item.unitName,
                specificationModel: item.specificationModel,
                inventoryClassName: item.inventoryClassName,
                quantity: 0,
                existingQuantity: '',
                stockRemark: ''
            })
        }
    }

    inventoryDialogVisible.value = false
    selectedInventory.value = [] // 清空已选
}


// 获取当前分页+搜索参数
const getParams = () => ({
    Code: searchModel.value.Code,
    page: currentPage.value,
    rows: pageSize.value
})

// 分页页码变化
const handleCurrentChange = (page) => {
    currentPage.value = page
    Search()
}

// 分页每页条数变化
const handleSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    Search()
}

// 查询方法（分页变化，自动渲染，条件搜索）
const Search = async () => {
    loading = true
    const params = getParams()
    console.log("已执行params：", params)
    try {
        const result = await MaterialOutboundOrderSearch(params)
        if (result.status === 0) {
            detailTableData.value = result.rows || []
            totalCount.value = result.total || 0
            loading = false
        } else {
            detailTableData.value = []
            totalCount.value = 0
            ElMessage.error(result.msg || '查询失败')
        }
    } catch (error) {
        console.error('查询异常:', error)
    }
}

// 搜索按钮（复用 Search，并且重置页码）
const SearchList = () => {
    currentPage.value = 1
    Search()
}


// 订单明细下部分
const showOrderDetailData = async () => {
    const id = orderDetail.value.id
    const result = await orderDetailSearchList(id)
    orderInfodetail.value = result.rows
}

// 订单明细上部分
const showOrderDetail = (row) => {
    orderDetail.value = { ...row }
    detailDialogVisible.value = true
    console.log(orderDetail.value)
    // showOrderDetailData()
}

// 弹窗滚动控制
watch(() => detailDialogVisible.value, (val) => {
    document.body.style.overflow = val ? 'hidden' : ''
})

// 初始化
Search()


</script>

<style scoped>
.table-container {
    /* background-color: #ffffff; */
    /* border: 1px solid #ebeef5; */
    border-radius: 10px;
    /* padding: 20px; */
    /* margin-bottom: 30px; */
    /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05); */
}

/* 表格滚动容器 */
.table-scroll-wrapper {
    /* height: 500px; */
    /* 固定表格高度 */
    overflow: auto;
    /* 表体滚动 */
}

/* 表头固定 */
/* .el-table th {
    position: sticky;
    top: 0;
    background: #fff;
    z-index: 10;
} */

/* 表格文字居中 */
::v-deep(.el-table th, .el-table td) {
    text-align: center;
}

/* 其他样式保持不变 */
.section-title {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 16px;
    color: #333;
    padding-bottom: 6px;
    border-bottom: 2px solid #333;
    display: inline-block;
}
</style>

<style lang="less" scoped>
@import "@/assets/css/index.less";
::v-deep {
    .el-container {
        display: block;
    }
    .el-table thead {
        color: #616161 !important;
    }
    .el-table th.el-table__cell {
        background-color: #f8f8f9 !important;
    }
}
</style>

<style lang="less" scoped>
.plan-dialog {
    .table-pagination {
    display: flex;
    justify-content: flex-end;
    padding: 2px 28px;
    border: 1px solid #eee;
    border-top: 0px;
    }

    .pagination {
    text-align: right;
    padding: 2px 28px;
    border: 1px solid #eee;
    border-top: 0px;
    }

    ::v-deep {
        .el-dialog__header {
            text-align: center;
            border-bottom: 1px solid #DCDFE6;
            margin-right: 0 !important;
            margin-bottom: 10px;
        }
    }
}
</style>

